/*
 * HttpClient.c
 *
 *  Created on: 19.07.2011
 *      Author: sili
 */

#include "HttpClient.h"
#include "PropertyFactory.h"

static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("at.sili.aalsystem.factories.HttpClient"));

static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;

HttpClient::HttpClient(Controller * _controller)
	: ActionListener("HttpClient"){
	this->controller = _controller;
	this->controller->addListener(this);

	this->actions.clear();
	this->Start();

	AAL_DEBUG(logger,"Constructor");
}

HttpClient::~HttpClient() {
	AAL_DEBUG(logger,"Destructor");
}

void HttpClient::Action(void){
	while(Running()){
		pthread_mutex_lock( &count_mutex );
		pthread_cond_wait(&condition_var, &count_mutex );

		if(this->actions.size() > 0){
			AALAction * action = this->actions.back();
			CURL * curl = curl_easy_init();
			CURLcode res;

			if(curl) {
				curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 10000);
				curl_easy_setopt(curl, CURLOPT_URL, action->data.c_str());
				res = curl_easy_perform(curl);

				AAL_DEBUG(logger,"Action %s retured: %d", action->data.c_str(), res);

				/* always cleanup */
				curl_easy_cleanup(curl);
			}
			this->actions.pop_back();
		}
		pthread_mutex_unlock( &count_mutex );
	}
}

void HttpClient::doAction(AALAction * _action){
	if(_action->type == doSetValue){
		AAL_INFO(logger, "%s doAction id:%ld type: %s message:\"%s\" aalItemId:%d", ((ActionListener*)this)->getName(),_action->id, _action->typeToString(), _action->message.c_str(), _action->aalItem != NULL ? _action->aalItem->getId():-1);

		pthread_mutex_lock( &count_mutex );

		const char * serverHost = this->controller->getPropertyFactory()->getStringProperty(AALPROP_AALBACKEND_HOST);
		int serverPort = this->controller->getPropertyFactory()->getIntProperty(AALPROP_AALBACKEND_PORT);

		int value = 0;
		try{
			value = Tools::getIntFromString(_action->message.c_str());
			AAL_DEBUG(logger, "doAction, value %d", value);
		}catch (...) {
			AAL_WARN(logger, "doAction, can't parse _action->message \"%s\" to int",  _action->message.c_str());
		}

		//http://192.168.60.120:8088/vdr?action=setValue&itemId=2&value=0
		char url[1000];
		snprintf(url, (size_t)999, "http://%s:%d/vdr?action=setValue&itemId=%d&value=%d", serverHost, serverPort, _action->aalItem != NULL ? _action->aalItem->getId():-1, value);

		AALAction * newAction = new AALAction(_action->type,_action->aalItem,"",0,this->controller);
		newAction->data = url;
		this->actions.push_back(newAction);

		pthread_cond_signal( &condition_var );
		pthread_mutex_unlock( &count_mutex );

	}
}

void HttpClient::doMainSavedAction(){

}

